package com.example.springbootlean.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springbootlean.entity.UserTest;
import com.example.springbootlean.mapper.UserTestMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 测试连接Mybatis-plus
 */
@RestController
//@RequestMapping("api/v1/test/my/")
@Slf4j
public class TestMyController {

    //如果出现红色下划线不影响运行，可以设置idea不报红
    @Autowired
    private UserTestMapper userTestMapper;

    /**
     * 查询所有用户信息
     */
    @GetMapping("/")
    public List<UserTest> test(){

        //直接调用BaseMapper封装好的CRUD方法，就可实现无条件查询数据
        List<UserTest> list = userTestMapper.selectList(null);

        //循环获取用户数据
        for (UserTest userTest: list){
            //获取用户名称
            System.out.println(userTest.getUsername());
        }

        return list;
    }

    @PostMapping("insert")
    public Integer insert(@RequestBody UserTest body) {
//        UserTest user = new UserTest().setAge(12).setTel(12).setUsername("steven").setVersion(10).setType(0);
//        body.setCreate_time(new Date());
        int insert = userTestMapper.insert(body);
        return insert;
    }

    @GetMapping("page")
    public Page<UserTest> page(@RequestParam("current") int current, @RequestParam("size") int size) {
        log.info("page current={} size={}", current, size);

        //step1: 创建一个 Page对象 从0开始
        Page<UserTest> page = new Page<>(current, size);

        // Step2：调用 mybatis-plus 提供的分页查询方法  .getRecords取出集合数据 不取的话会返回一些其它值
//        LambdaQueryWrapper<UserTest> query = new LambdaQueryWrapper<UserTest>().eq(UserTest::getAge, 12);
        Page<UserTest> userTestPage = userTestMapper.selectPage(page, null);

        return userTestPage;
    }

}

